#!/usr/bin/env ruby
#-*- coding:utf-8 -*-

require "readline"
require "./mail.rb"

CMD_LIST = [
  'help', 'quit', 'users', 'useradd', 'userdel',
  'groups', 'groupadd', 'groupdel', 'refresh'
].sort

HELP_MSG = <<EOF
help          显示该帮助信息
quit          退出
users         显示所有用户
useradd       添加用户  eg: useradd nickname username password
userdel       删除用户  eg: userdel name
groups        显示所有组
groupadd      添加组 eg: groupadd name
groupdel      删除组 eg: groupdel name
refresh       刷新
EOF

comp = proc { |s| CMD_LIST.grep(/^#{Regexp.escape(s)}/) }

Readline.completion_append_character = " "
Readline.completion_proc = comp

def main_loop username, passwd, domain
  m = YMMail::Mail.new username, passwd, domain

  puts HELP_MSG
  while buf = Readline.readline("> ", true)
    command = buf.strip
    if command == "" then
      next
    end
    if command == "quit" then
      puts "Goodbye.."
      exit
    end
    if command == "help" then
      puts HELP_MSG
    end
    cmd, *args = command.split
    if !CMD_LIST.include?(cmd) then
      next
    end
    if cmd == "users" then
      m.user_list
      next
    elsif cmd == "groups" then
      m.group_list
      next
    elsif cmd == "groupdel" then
      if args.length == 0
        puts "Usage: groupdel name"
        next
      end
      m.delete_group args[0].strip
      next
    elsif cmd == "groupadd" then
      if args.length == 0
        puts "Usage: groupadd name"
        next
      end
      m.add_group args[0].strip
      next
    elsif cmd == "userdel" then
      if args.length == 0
        puts "Usage: userdel name"
        next
      end
      m.delete_user args[0].strip
      next
    elsif cmd == "useradd" then
      if args.length < 3
        puts "Usage: useradd nickname username passwd"
        next
      end
      m.add_user args[0].strip, args[1].strip, args[2].strip
      next
    elsif cmd == "refresh" then
      m.parse_user_list
      next
    end
    puts "#{cmd} #{args}"
  end
end

if caller.length == 0 then
  require "io/console"
  print "请输入域名："
  domain = gets
  print "请输入用户名："
  username = gets
  print "请输入密码："
  io = IO.console
  io.echo=false
  passwd = gets
  io.echo=true
  puts ""
  main_loop username.strip, passwd.strip, domain.strip
end
